﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure.StorageClient;
using System.IO;

namespace Microsoft.WindowsAzure.StorageClient
{
	public static class BlobExtensions
	{
		public static bool ContainerExists(this CloudBlobClient client, string containerName)
		{
			try
			{
				return client.GetContainerReference(containerName).Exists();
			}
			catch (StorageClientException e)
			{
				switch (e.ErrorCode)
				{
					case StorageErrorCode.ResourceNotFound:
					case StorageErrorCode.BadRequest:
						return false;
				}

				Console.WriteLine("ERROR: {0}", e);

				return false;
			}
		}

		public static bool ContainerOrDirectoryExists(this CloudBlobClient client, string containerName)
		{
			return client.ContainerExists(containerName) || client.DirectoryExists(containerName);
		}

		public static bool DirectoryExists(this CloudBlobClient client, string directoryName)
		{
			try
			{
				return client.GetBlobDirectoryReference(directoryName).ListBlobs().Any();
			}
			catch (StorageClientException e)
			{
				switch (e.ErrorCode)
				{
					case StorageErrorCode.ResourceNotFound:
					case StorageErrorCode.BadRequest:
						return false;
				}

				Console.WriteLine("ERROR: {0}", e);

				return false;
			}
		}

		public static CloudBlobContainer GetLowestContainer(this CloudBlobClient client, string fileName)
		{
			CloudBlobContainer result = null;

			string containerPath = Path.GetDirectoryName(fileName);

			while (containerPath.Length > 0)
			{
				result = client.GetContainerReference(containerPath);

				if (result.Exists())
				{
					return result;
				}

				containerPath = Path.GetDirectoryName(fileName);
			}

			return result;
		}

		public static bool Exists(this CloudBlob blob)
		{
			try
			{
				blob.FetchAttributes();

				return true;
			}
			catch (StorageClientException e)
			{
				if (e.ErrorCode == StorageErrorCode.ResourceNotFound)
				{
					return false;
				}
				else
				{
					Console.WriteLine("ERROR: {0}", e);

					//throw;

					return false;
				}
			}
		}

		public static bool Exists(this CloudBlobContainer container)
		{
			try
			{
				container.GetPermissions();

				return true;
			}
			catch (StorageClientException e)
			{
				switch (e.ErrorCode)
				{
					case StorageErrorCode.ResourceNotFound:
					case StorageErrorCode.BadRequest:
						return false;
				}

				Console.WriteLine("ERROR: {0}", e);

				return false;
			}
		}
	}
}
